package com.sinder.campus_prophet.service.jwgl.impl;

import cc.lyceum.api.thxy.jwgl.ThxyJwgl;
import cc.lyceum.api.thxy.jwgl.pojo.ExamResults;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sinder.campus_prophet.core.global.ResponseMessage;
import com.sinder.campus_prophet.entity.jwgl.TbAchievement;
import com.sinder.campus_prophet.exception.JwglException;
import com.sinder.campus_prophet.mapper.jwgl.TbAchievementMapper;
import com.sinder.campus_prophet.mapper.jwgl.TbJwglInfoMapper;
import com.sinder.campus_prophet.service.jwgl.TbAchievementService;
import com.sinder.campus_prophet.service.jwgl.bean.dto.AchievementDto;
import com.sinder.campus_prophet.service.jwgl.bean.dto.AchievementSynDto;
import com.sinder.campus_prophet.service.jwgl.bean.dto.MyExamDto;
import com.sinder.campus_prophet.service.jwgl.bean.vo.AchievementVo;
import com.sinder.campus_prophet.service.jwgl.bean.vo.JwglInfoVo;
import com.sinder.campus_prophet.utils.TermCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author AS
 * @description 针对表【tb_achievement(成绩信息)】的数据库操作Service实现
 * @createDate 2023-03-20 22:58:05
 */
@Service
@Slf4j
public class TbAchievementServiceImpl extends ServiceImpl<TbAchievementMapper, TbAchievement>
        implements TbAchievementService {

    private final TbJwglInfoMapper jwglInfoMapper;

    private final TbAchievementMapper achievementMapper;

    public TbAchievementServiceImpl(TbJwglInfoMapper jwglInfoMapper, TbAchievementMapper achievementMapper) {
        this.jwglInfoMapper = jwglInfoMapper;
        this.achievementMapper = achievementMapper;
    }

    /**
     * 查询用户个人学期参数
     * @param openId
     * @return
     */
    @Override
    public ResponseMessage getJwglXqParam(String openId) {
        JwglInfoVo jwglInfoVo = jwglInfoMapper.getJwglInfo(openId);
        if (jwglInfoVo == null) {
            return ResponseMessage.createByErrorMessage("用户不存在");
        }
        String rxnf = jwglInfoVo.getRxnf();
        List<TermCodeUtils.YermCode> xqParam = TermCodeUtils.getTermCode(rxnf);
        return ResponseMessage.createBySuccess(xqParam);
    }

    /**
     * 成绩查询
     *
     * @param achievementDto
     * @return
     */
    @Override
    public ResponseMessage getAchievementList(AchievementDto achievementDto) {
        List<AchievementVo> achievementVoList = achievementMapper.getAchievementList(achievementDto);
        if (achievementVoList.size() == 0) {
            return ResponseMessage.createByErrorMessage("暂无数据，请移步同步数据");
        }
        return ResponseMessage.createBySuccess("个人成绩", achievementVoList);
    }

    /**
     * 成绩同步 单独同步教务系统数据
     *
     * @param achievementDto
     * @return
     */
    @Async("taskExecutor")
    @Override
    public ResponseMessage synAchievementData(AchievementSynDto achievementDto, ThxyJwgl jwgl) {
        log.info(Thread.currentThread().getThreadGroup() + "--------" + Thread.currentThread().getName());
        String openId = achievementDto.getOpenId();
        // 数据同步开始时间
        long start = System.currentTimeMillis();
        // 1：登录教务系统
        try {
            // 3：获取成绩信息 -- 每个人共有八个学期 -- 数据同步前先清空相关用户旧数据
            QueryWrapper<TbAchievement> achievementDelQuery = new QueryWrapper<>();
            achievementDelQuery.eq("wx_open_id", openId);
            int achDelRow = achievementMapper.delete(achievementDelQuery);
            log.info("----已清空用户openId为：{}的成绩信息{}条数据，正在同步新数据----", openId, achDelRow);
            // 根据入学年份获取四年学期参数 202001 == 大一(上) -- 入学年份插入教务信息表
            String rxnf = jwgl.getStudentInfo().getRxnf(); // 获取入学年份
            // 个人学期参数列表
            List<TermCodeUtils.YermCode> yermCodeList = TermCodeUtils.getTermCode(rxnf);
            for (TermCodeUtils.YermCode yerm : yermCodeList) {
                List<ExamResults> examList = jwgl.getExamResults(yerm.getCode());
                // 无数据则不进行处理
                if (examList.size() == 0) {
                    continue;
                }
                // 数据处理
                List<TbAchievement> achievementList = examList.stream().map(item -> {
                    TbAchievement achievement = new TbAchievement();
                    BeanUtils.copyProperties(item, achievement);
                    achievement.setSynTime(new Date());
                    achievement.setWxOpenId(openId);
                    return achievement;
                }).collect(Collectors.toList());
                // 批量入库
                achievementMapper.insertBatch(achievementList);
            }
        } finally {
            // 结束后退出登录
            if (jwgl != null) {
                jwgl.logout();
            }
        }
        // 数据同步结束时间
        long end = System.currentTimeMillis();
        log.info("个人成绩已同步，共耗时：" + (end-start) / 1000 + "s" );
        return ResponseMessage.createBySuccessMessage("个人成绩已同步，共耗时：" + (end-start) / 1000 + "s");
    }
}




